package com.bvr;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;

import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
//import android.widget.ImageView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class LoginActivity extends Activity {
	/** Called when the activity is first created. */
	private Button btnLogin;
	EditText txtUserName;
	TextView lblMsg;
	EditText txtPassword;
	CheckBox chkIsRemembered;

	private Runnable runableLogin;
	private ProgressDialog m_ProgressDialog = null;

	private static String serviceResponse;
	private static String userName;
	private static String password;
	private static String strMsg;
	private static boolean isAuthenticate;

	private SharedPreferences appSettings;
	private static String URL = "";
	private static String METHOD_NAME = "";
	private static String NAMESPACE = "";
	private static String SOAP_ACTION = "";

	private Button btnTemp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
		appSettings = getSharedPreferences("BVRAppPreferences", MODE_PRIVATE);
		setVariables();
		SetUI();
		Boolean isRemembered = appSettings.getBoolean("isRemembered", false);
		chkIsRemembered.setChecked(isRemembered);

		if (isRemembered) {
			txtUserName.setText(appSettings.getString("userName", ""));
			txtPassword.setText(appSettings.getString("password", ""));
		}
	}

	private void setVariables() {
		URL = getString(R.string.url_login);
		METHOD_NAME = getString(R.string.method_name_login);
		NAMESPACE = getString(R.string.namespace_login);
		SOAP_ACTION = getString(R.string.soap_action_login);
	}

	private void SetUI() {
		btnLogin = (Button) findViewById(R.id.buttonLogin);
		btnLogin.setOnClickListener(loginListener);

		btnTemp = (Button) findViewById(R.id.btnTemp);
		btnTemp.setOnClickListener(tempListener);

		btnTemp.setVisibility(View.GONE);

		txtUserName = (EditText) findViewById(R.id.txtUserName);

		txtPassword = (EditText) findViewById(R.id.txtPassword);

		txtPassword.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_GO) {
					startLogin();
				}
				return false;
			}

		});

		chkIsRemembered = (CheckBox) findViewById(R.id.chkRememberPassword);
		lblMsg = (TextView) findViewById(R.id.lblMsg);
	}

	private OnClickListener tempListener = new OnClickListener() {
		public void onClick(View view) {
			Intent myIntent = new Intent(view.getContext(), TempActivity.class);
			startActivityForResult(myIntent, 0);
		}
	};

	private Boolean startLogin() {
		try {
			if (!isValidate()) {
				MessageBox("Not valid user id or password");
				return false;
			}

			if (!isNetworkAvailable()) {
				MessageBox("No active connection found, check your internet");
				return false;
			}

			userName = txtUserName.getText().toString();
			password = txtPassword.getText().toString();

			runableLogin = new Runnable() {
				@Override
				public void run() {
					authenticate();
				}
			};

			Thread thread = new Thread(null, runableLogin, "MagentoBackground");
			thread.start();
			m_ProgressDialog = ProgressDialog.show(LoginActivity.this,
					"Please wait...", "Authenticating ...", true);

		} catch (Exception e) {

		}

		return true;
	}

	private Runnable returnRes = new Runnable() {
		@Override
		public void run() {

			m_ProgressDialog.dismiss();
			doLogin();
		}
	};

	private void doLogin() {
		if (isAuthenticate) {
			SharedPreferences.Editor prefEditor = appSettings.edit();
			if (chkIsRemembered.isChecked()) {
				prefEditor.putString("userName", userName);
				prefEditor.putString("password", password);
				prefEditor.putBoolean("isRemembered", true);
			} else {
				prefEditor.putString("userName", "");
				prefEditor.putString("password", "");
				prefEditor.putBoolean("isRemembered", false);
			}
			prefEditor.commit();
			Intent myIntent = new Intent(this.getBaseContext(),
					HomeActivity.class);
			startActivityForResult(myIntent, 0);
		} else {
			MessageBox(strMsg);
		}

	}

	private OnClickListener loginListener = new OnClickListener() {
		public void onClick(View view) {
			// doLogin();
			startLogin();
		}
	};

	private void authenticate() {
		Boolean flag = false;
		try {
			parseWebService(userName, password);
			if (serviceResponse == null
					|| serviceResponse.compareToIgnoreCase("") == 0
					|| serviceResponse.compareToIgnoreCase("0") == 0) {
				flag = false;
				strMsg = "Invalid user name or password";
			} else {
				String ownerId = serviceResponse.toString().substring(0,
						serviceResponse.toString().indexOf("|"));
				String propertyCount = serviceResponse.toString().substring(
						ownerId.length() + 1,
						serviceResponse.toString().length());
				SharedPreferences.Editor prefEditor = appSettings.edit();
				prefEditor.putString("ownerID", ownerId);
				prefEditor.putString("propertyCount", propertyCount);
				prefEditor.commit();
				flag = true;
			}

		} catch (IOException e) {
			flag = false;
			strMsg = "Could not authenticate due to some problem";
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			flag = false;
			strMsg = "Could not authenticate due to some problem";
			e.printStackTrace();
		} catch (JSONException e) {
			flag = false;
			strMsg = "Could not authenticate due to some problem";
			e.printStackTrace();
		}

		isAuthenticate = flag;
		runOnUiThread(returnRes);
	}

	private boolean isNetworkAvailable() {
		NetworkInfo activeNetworkInfo;
		try {
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		} catch (Exception ex) {
			// Toast.makeText(this, ex.getMessage(), 10);
			// lblMsg.setText(ex.getMessage());
			return false;
		}
		return activeNetworkInfo != null;
	}

	private Boolean isValidate() {
		String userName = txtUserName.getText().toString();
		String password = txtPassword.getText().toString();

		if (userName == "" || password == "") {
			return false;

		}
		return true;

	}

	private String[] splitString(String original, String separator) {

		Vector nodes = new Vector();

		// Parse nodes into vector
		int index = original.indexOf(separator);

		while (index >= 0) {
			nodes.addElement(original.substring(0, index));

			original = original.substring(index + separator.length());

			index = original.indexOf(separator);

		}
		// Get the last node
		nodes.addElement(original);

		// Create split string array
		String[] result = new String[nodes.size()];

		if (nodes.size() > 0) {

			for (int loop = 0; loop < nodes.size(); loop++)

			{
				result[loop] = (String) nodes.elementAt(loop);

				// System.out.println(result[loop]);

			}

		}
		return result;

	}

	public void MessageBox(String message) {
		AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		alertbox.setMessage(message);

		alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				// Toast.makeText(getApplicationContext(), "OK button clicked",
				// Toast.LENGTH_LONG).show();
			}
		});
		alertbox.show();
	}

	/* Web Service Parsing */

	private void parseWebService(String userName, String password)
			throws IOException, XmlPullParserException, JSONException {

		String result = "";
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		request.addProperty("userName", userName);
		request.addProperty("password", password);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;

		envelope.implicitTypes = true;
		envelope.encodingStyle = "utf-8";
		envelope.enc = SoapSerializationEnvelope.ENC2001;
		envelope.xsd = SoapEnvelope.XSD;
		envelope.xsi = SoapEnvelope.XSI;

		envelope.setOutputSoapObject(request);
		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		envelope.addMapping(NAMESPACE, "AuthenticateUser",
				new PropertyDetail().getClass());
		androidHttpTransport.call(SOAP_ACTION, envelope);
		androidHttpTransport
				.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

		androidHttpTransport.debug = true;
		String soapresultmsg = envelope.getResponse().toString();
		result = soapresultmsg;

		try {

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		serviceResponse = result.trim();
		// m_ProgressDialog.dismiss();
	}

	public void debugDisplay(String s) {
		System.out.println(s);
	}
}